package com.zhy.generator.codegen.mybatis.javahelper.elements;

import com.zhy.generator.codegen.api.IntrospectedColumn;
import com.zhy.generator.codegen.dom.java.*;
import com.zhy.generator.codegen.mybatis.RootClassInfo;
import com.zhy.generator.codegen.mybatis.javahelper.JavaHelperMethodConstant;
import com.zhy.generator.codegen.mybatis.javarequest.RequestInnerClassConstant;

import java.util.List;

import static com.zhy.generator.codegen.util.JavaBeansUtil.*;

/**
 * @author 源
 */
public class AddParamToPOMethodGenerator extends AbstractJavaHelperMethodGenerator {

    @Override
    public void addHelperElements(TopLevelClass tlc) {
        Method method = new Method(getMethodStr());
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setStatic(true);
        tlc.addMethod(method);

        String requestType = introspectedTable.getRequestType();
        String paramTypeString = requestType + "." + RequestInnerClassConstant.ADD_PARAM;

        FullyQualifiedJavaType paramType = new FullyQualifiedJavaType(paramTypeString);
        String paramName = getCamelCaseString(paramType.getShortName(), false);
        Parameter p = new Parameter(paramType, paramName);
        method.addParameter(p);
        tlc.addImportedType(paramType);

        FullyQualifiedJavaType poType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        String poName = getCamelCaseString(poType.getShortName(), false);
        method.setReturnType(poType);

        method.addBodyLine(poType.getShortName() + " " + poName + " = new " + poType.getShortName() + "();");
        List<IntrospectedColumn> allColumns = introspectedTable.getNonPrimaryKeyColumns();

        FullyQualifiedJavaType superClass = getSuperClass();
        RootClassInfo instance = RootClassInfo.getInstance(superClass.getFullyQualifiedName(), warnings);
        for (IntrospectedColumn column : allColumns) {
            if (instance.containsProperty(column)) {
                continue;
            }
            FullyQualifiedJavaType fqjt = column.getFullyQualifiedJavaType();
            String property = column.getJavaProperty();
            String getterMethodName = getGetterMethodName(property, fqjt);
            String setterMethodName = getSetterMethodName(property);

            method.addBodyLine(poName + "." + setterMethodName + "(" + paramName + "." + getterMethodName + "());");
        }

        method.addBodyLine("return " + poName + ";");

    }

    @Override
    public String getMethodStr() {
        return JavaHelperMethodConstant.ADDPARAM_TO_PO;
    }


}
